import { Component } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'apes-img-review',
  template: `
    <button [disabled]="files.length === 0" (click)="previewVisible=true">查看</button>
    <apes-modal [apesVisible]="previewVisible" [apesContent]="modalContent" [apesFooter]="null"
                (apesOnCancel)="previewVisible=false">
      <ng-template #modalContent>
        <img *ngFor="let file of files" [src]="file.realSrc" [ngStyle]="{ 'width': '100%', borderBottom: '2px solid red'}"/>
      </ng-template>
    </apes-modal>
  `,
  styles: [],
})
export class RenderImageReviewComponent implements ICellRendererAngularComp {
  previewVisible: boolean = false;
  params: any;
  inputValue: any;
  prefix: '';
  split: '';
  files = [];
  constructor(
    private contextService: ApesContextMenuService,
    private http: HttpClient
  ) {}

  refresh(params: any): boolean {
    return false;
  }

  agInit(params: any): void {
    this.params = params;
    this.inputValue = this.params.value;
    this.prefix = params.prefix ? params.prefix : '';
    this.split = params.split ? params.split : ';';
    this.resolveImgSrc();
  }

  /** 判断是否显示预览图 **/
  handlePreview = () => {
    if( this.files && this.files.length > 0 ) {
      this.previewVisible = true;
    }
  };


  resolveImgSrc() {
    if (this.inputValue == null) this.files = [];

    this.files =  this.inputValue.map(url => {
      return {
        src: url,
        realSrc: url
      }
    });

    this.files.forEach(file => {
      if (!/\.TIF$/.test(file.src)) return;

      this.http.request("GET", file.src, {
        responseType:'arraybuffer',
      }).subscribe(response => {
        let tiff = new Tiff({buffer: response});
        file.realSrc = tiff.toDataURL();
      });
    })
  }




}
